package dev.pda.display.data.message

import android.util.Log
import com.google.gson.Gson
import dev.pda.display.data.SharedPrefs
import dev.pda.display.data.common.entity.ErrorResponse
import dev.pda.display.data.common.exceptions.HttpException
import dev.pda.display.data.message.entity.ResourceMessage
import dev.pda.display.domain.message.MessageRepository
import dev.pda.display.presentation.page.model.ProgramVM
import dev.pda.display.presentation.page.util.DataMapper
import dev.pda.display.util.TCPManager
import dev.pda.display.util.UDPManager
import dev.pda.display.util.mqtt.MqttManager
import io.reactivex.Single
import javax.inject.Inject

class MessageRepositoryImpl @Inject constructor(
    private val sharedPrefs: SharedPrefs
) : MessageRepository {

    override fun sendUDPManager(ipAddress: String, port: Int, message: String): Single<Boolean> {
        return Single.just(UDPManager.get().sendMessage(ipAddress, port, message))
    }

    override fun initUDPServer(ipAddress: String, port: Int): Single<Boolean> {
        return Single.create { emitter ->
            UDPManager.get().init(port)
            emitter.onSuccess(true)
            Log.e("mirror5821", "start-udp")
        }
    }

    override fun initTCPServer(port: Int): Single<Boolean> {
        return Single.create { emitter ->
            TCPManager.get().init(port)
            emitter.onSuccess(true)
            Log.e("mirror5821", "start-tcp")
        }
    }

    override fun connectMQTT(): Single<Boolean> {
        return Single.create { emitter ->
            MqttManager.getInstance().connect {
                onConnectSuccess {
                    emitter.onSuccess(true)
                }
                onConnectFailed {
                    it?.let { it1 -> emitter.onError(it1) }
                }
            }
        }
    }

    override fun disConnectMQTT(): Single<Unit> {
        return Single.create {
            MqttManager.getInstance().disconnect()
        }
    }

    override fun sendMQTTMessage(publishTopic: String, message: String): Single<Unit> {
        return Single.create {
            MqttManager.getInstance().publishMessage(publishTopic, message)
        }
    }

    override fun getProgramVM(message: String): Single<ProgramVM> {
        return Single.create { emitter ->
            val resourceMessage = Gson().fromJson(message, ResourceMessage::class.java)
            val programVM = DataMapper.resourceMessageConvertToProgramVM(resourceMessage)
            if (programVM == null) {
                emitter.tryOnError(HttpException(ErrorResponse("empty data")))

            } else {
                emitter.onSuccess(programVM)
            }
        }
    }
}